package club.hiuit.share.kuaidi100.api;

import club.hiuit.share.kuaidi100.entity.KuaidiProperties;
import club.hiuit.share.kuaidi100.entity.OrderRequsertData;
import club.hiuit.share.kuaidi100.entity.OrderResponseData;
import club.hiuit.share.kuaidi100.entity.PrintRecData;
import club.hiuit.share.kuaidi100.util.Kuaidi100MD5;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.List;

import static club.hiuit.share.kuaidi100.util.BeanUtil.requireNonNull;


@Slf4j
@Data
public class Kuaidi100NetCenter {

    private KuaidiProperties kuaidi100;

    public Kuaidi100NetCenter(KuaidiProperties kuaidi100) {
        requireNonNull(kuaidi100.getAppid(), "appid is null");
        requireNonNull(kuaidi100.getAppsecret(), "appid is null");
        requireNonNull(kuaidi100.getTimestamp(), "Timestamp is null");
        this.kuaidi100 = kuaidi100;
    }

    public String sign(String appuid) {
        requireNonNull(appuid, "appuid is null");
        String sign = Kuaidi100MD5.encode(kuaidi100.getAppsecret() + Kuaidi100MD5.encode(kuaidi100.getAppid() + kuaidi100.getTimestamp(true) + appuid));
        log.info("========>>sign:{}<<=====",sign);
        return sign;
    }



    /**
     * 订单信息导入
     *
     * @param orderRequsertData
     * @return
     */
    public OrderResponseData sendOrderRequsertData(OrderRequsertData orderRequsertData,String appuid) {
        requireNonNull(kuaidi100.getAppid(), "appid is null");
        requireNonNull(kuaidi100.getAppsecret(), "Appsecret is null");
        requireNonNull(kuaidi100.getTimestamp(), "Timestamp is null");

        // 表单提交 这种能满足大部分的需求

        kuaidi100.setTimestamp(System.currentTimeMillis());
        String string_order = JSONObject.toJSONString(orderRequsertData, SerializerFeature.WriteEnumUsingToString);
        log.info(string_order);

        RequestBody formBody = new FormBody.Builder()
                .add("appid", kuaidi100.getAppid()).add("appuid", appuid)
                .add("timestamp", String.valueOf(kuaidi100.getTimestamp())).add("sign", sign(appuid))
                .add("data", string_order)
                .build();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://b.kuaidi100.com/v4/open/api.do?method=send")
//                .header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                // 表单提交
                .post(formBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                log.info(json);
                OrderResponseData orderResponseData = JSONObject.parseObject(json, OrderResponseData.class);
                return orderResponseData;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //订单信息修改接口
    public OrderResponseData modificationOrder(OrderRequsertData orderRequsertData,String appuid){

        String string_order = JSONObject.toJSONString(orderRequsertData, SerializerFeature.WriteEnumUsingToString);
        log.info(string_order);
        OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("appid", kuaidi100.getAppid()).add("appuid", appuid)
                .add("timestamp", String.valueOf(kuaidi100.getTimestamp())).add("sign", sign(appuid))
                .add("data", string_order)
                .build();

        Request request = new Request.Builder()
                .url("http://b.kuaidi100.com/v4/open/api.do?method=update")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                // 表单提交
                .post(formBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                log.info(json);
                OrderResponseData orderResponseData = JSONObject.parseObject(json, OrderResponseData.class);
                return orderResponseData;
            }
        } catch (IOException e) {
            log.info("============网络异常==============");
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 快速列表打印
     * @param list
     */
    public String printlistDo(List<String> list, String appuid) {
        requireNonNull(appuid, "appuid is null");
        requireNonNull(list, "list is null");
        log.info("=========快速列表打印============");
        String get_list = null;
        for (String s : list) {
            if ( get_list == null ){
                get_list = s;
            }else {
                get_list += "," + s;
            }
        }
        HttpUrl url = HttpUrl.parse("http://b.kuaidi100.com/v4/open/api.do").newBuilder()
                .addQueryParameter("method", "print")
                .addQueryParameter("appid", kuaidi100.getAppid())
                .addQueryParameter("appuid",appuid)
                .addQueryParameter("timestamp", String.valueOf(kuaidi100.getTimestamp()))
                .addQueryParameter("sign", sign(appuid))
                .addQueryParameter("printlist",get_list)
                .build();
        Request request = new Request.Builder()
                .url(url).get().build();
        log.info("========>>url:{}<<===========" + url.url().toString());
//        OkHttpClient client = new OkHttpClient();

//        try {
//            Response response = client.newCall(request).execute();
//            if (response.isSuccessful()) {
//                String json = response.body().string();
//                log.info(json);
//                return json;
//            }
//        } catch (IOException e) {
//            log.info("=========快速列表打印失败网络失败=========");
//            e.printStackTrace();
//            log.info(e.getMessage());
//        }
        return url.url().toString();
    }


    /**
     * 自动打印
     * @param list
     * @param appuid
     */
    public PrintRecData automaticPrinting(List<String> list,String appuid){
        requireNonNull(appuid, "appuid is null");
        log.info("=========自动打印============");
        String post_list = null;
        for (String s : list) {
            if ( post_list == null ){
                post_list = s;
            }else {
                post_list += "," + s;
            }
        }
        log.info("==========>post_list:{}=========",post_list);
        RequestBody formBody = new FormBody.Builder()

                .add("appid", kuaidi100.getAppid()).add("appuid", appuid)
                .add("timestamp", String.valueOf(kuaidi100.getTimestamp())).add("sign", sign(appuid))
                .add("printlist",post_list)
                .build();

        Request request = new Request.Builder()
                .url("http://b.kuaidi100.com/v4/open/api.do?method=autoPrint")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .post(formBody).build();

        log.info("==========>request:{}=========",request.toString());
        OkHttpClient client = new OkHttpClient();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                log.info(json);
                PrintRecData printRecData = JSONObject.parseObject(json, PrintRecData.class);
                return printRecData;
            }
        } catch (IOException e) {
            log.info("=========自动打印打印失败=========");
            e.printStackTrace();
        }
        return null;
    }

}






















